﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Data.SqlClient;

namespace JFLERP.IQ
{
    public partial class SAPMaterialMasterList : DevExpress.XtraEditors.XtraForm, IMdiChildActions
    {


        public SAP_MM_P AccessType { get; set; }



        public SAPMaterialMasterList()
        {
            InitializeComponent();


        }

        #region IMdiChildActions 成员

        public void Save()
        {

        }

        public void New()
        {

        }

        public void Delete()
        {

        }

        public void Print()
        {

        }

        public void SelectAll()
        {

        }

        public void Find()
        {

        }

        public void Export()
        {

        }

        #endregion



        private void GetDataFromSystem(SAP_MM_P StepNumber)
        {

            try
            {
                if (chk_CurrentStatus.Checked)
                {
                    DbHelperSQL.ExecuteSql("exec sp_InitExtendingStatusOfSAPData ");
                }
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append("SELECT PE_Date=convert(nvarchar(19),sim.PE_Date,121), ");
                sbSql.Append("GC_Date=convert(nvarchar(19),sim.GC_Date,121), ");
                sbSql.Append("PL_Date=convert(nvarchar(19),sim.PL_Date,121), ");
                sbSql.Append(" Plant='CN02' ");
                sbSql.Append(" ,Purchasing_CostTax=CASE WHEN  CAST( ISNULL(sim.Purchasing_Cost,0)*1.03 AS DECIMAL(18,2))<1 THEN -999 ELSE CAST( ISNULL(sim.Purchasing_Cost,0)*1.03 AS DECIMAL(18,2)) END ");
                sbSql.Append(",Plannedpricedate1=CONVERT(VARCHAR(8),GETDATE(),112), ");

                sbSql.Append("PO_Date=convert(nvarchar(19),sim.PO_Date,121), ");
                sbSql.Append("SendToPOFlag=CASE  sim.Procurement_Type WHEN 'F' THEN  ISNULL(sim.SendToPOFlag,'-')  ELSE 'X' END,");
                sbSql.Append("LastMactchTime=convert(nvarchar(19),sim.LastMactchTime,121), ");
                sbSql.Append("LastUploadTime=convert(nvarchar(19),sim.LastUploadTime,121), ");
                sbSql.Append("T4SStatus=case  isnull(T4SStatus,'') when '' then '-' else T4SStatus end,");
                sbSql.Append("CreateDate=convert(nvarchar(10),sim.CreateDate,121),IsMissPOview, ");
                sbSql.Append("sim.Plant_sp_matl_status, ");


                sbSql.Append("ProdHierarchyFlag= CASE  isnull(sim.ProductHierarchy,'') when  sim.V_ProdHierarchy_SALES THEN  'Y' ");
                sbSql.Append("                            WHEN  '' THEN '-' ");
                sbSql.Append("                             ELSE 'N' END , ");
                sbSql.Append("Prod_HierarchyName=sph.Prod_Hierarchy, ");
                sbSql.Append(" EditStatus='N',sim.* FROM SAP_ItemMaster sim ");
                sbSql.Append("LEFT JOIN SAP_MVKE sk ON sim.Material_Number=sk.Material ");
                sbSql.Append("LEFT JOIN SAP_ProductHierarchy sph ON sph.Prod_Hierarchy_Code=sk.Product_Hierarchy ");

                sbSql.Append("WHERE 1=1  ");
                if (chkIsAll.Checked)
                {
                    sbSql.Append(" AND isnull(sim.ActiveStatus,'')!='X' ");

                    switch (StepNumber)
                    {
                        case SAP_MM_P.PL:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMddhhmmss_") + "计划填写.xlsx";
                            sbSql.Append("  AND  sim.Procurement_Type IN ('E','X') ");
                            sbSql.Append("  AND isnull(sim.MRP_Type_PL,'')='' ");
                            break;
                        case SAP_MM_P.PE:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMddhhmmss_") + "工艺填写.xlsx";
                            sbSql.Append("AND  isnull(sim.Procurement_Type,'') ='' ");

                            break;
                        case SAP_MM_P.PO:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMddhhmmss_") + "采购填写.xlsx";
                            sbSql.Append("AND  sim.Procurement_Type IN ('F','X') ");
                            sbSql.Append(" and isnull(sim.Purchasing_Cost,0)=0 AND isnull(sim.MRP_Type,'')=''  And isnull(T4SStatus,'')!=''");
                            break;
                        case SAP_MM_P.SAPUpload:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMddhhmmss_") + "数据录入.xlsx";
                            sbSql.Append("AND  sim.Procurement_Type IN ('F','X','E') ");
                            sbSql.Append(" and (isnull(sim.V_MRP,'')=''  OR ISNULL( sim.V_PLANT_STORAGE_LOC,'')='') ");
                            break;
                        case SAP_MM_P.FIN:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMddhhmmss_") + "数据录入.xlsx";
                            sbSql.Append("AND sim.Procurement_Type IN ('F','E') ");
                            sbSql.Append("AND sim.Purchasing_Cost>0 ");
                            sbSql.Append("AND sim.V_PROCUREMENT_TYPE='F' ");
                            sbSql.Append("AND sim.V_MATERIAL_PLANT_STATUS='ZE' ");

                            break;
                        case SAP_MM_P.SYCHN:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMddhhmmss_") + "数据录入.xlsx";
                            sbSql.Append("AND sim.NeedToSynch ='Y' ");
                            break;
                        default:
                            txtFileName.Text = DateTime.Now.ToString("yyyyMMdd_HHmmss_") + "All Data.xlsx";
                            if (txt_MaterialNumber.Text.Trim() != "")
                            {
                                if (txt_MaterialNumber.Text.Contains(",") == false)
                                {
                                    sbSql.AppendFormat(" And Material_Number like '%{0}%'", txt_MaterialNumber.Text);
                                }
                                else
                                {
                                    sbSql.AppendFormat("AND Material_Number IN ({0}) ", CFunctionUtility.CFListToString(txt_MaterialNumber.Text.Trim(), ','));
                                }
                            }
                            if (txt_BIReportName.Text.Trim() != "")
                            {
                                //sbSql.AppendFormat(" And Material_Description like '%{0}%'", txt_BIReportName.Text);
                            }

                            break;
                    }

                    sbSql.Append(" Order by sim.CreateDate desc");

                    System.Data.DataTable dt = new System.Data.DataTable();
                    if (txt_BIReportName.Text == "" && txt_MaterialNumber.Text != "")
                    {
                        dt = DbHelperSQL.Query(sbSql.ToString()).Tables[0];
                    }
                    else
                    {
                        dt = DbHelperSQL.Query("EXEC sp_BIReport_MaterialMaster '" + txt_BIReportName.Text + "'").Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            txtFileName.Text = dt.Rows[0]["BIName"].ToString() + ".xlsx";
                            txt_BIReportName.Text = dt.Rows[0]["BIName"].ToString();
                        }
                    }
                    DataRow dr = dt.NewRow();
                    //dt.Rows.Add(dr);
                    this.gdc_MpsMain.DataSource = dt;

                    this.Text = "SAP 物料主数据跟踪[" + dt.Rows.Count.ToString() + "]条记录.";

                    this.xtraTabControl1.SelectedTabPageIndex = 0;
                    if (chk_KPI.Checked)
                    {

                        DataSet ds = DbHelperSQL.Query("exec sp_DailyreportOfDataExtending 'Y'");
                        this.gridControl1.DataSource = ds.Tables[0];
                        this.gridControl2.DataSource = ds.Tables[1];
                    }
                    this.bandedGridColumn_Delay_CG.BestFit();
                    this.bandedGridColumn_Delay_GY.BestFit();
                    this.bandedGridColumn_MASSGROUP.BestFit();
                    this.bandedGridColumn_Delay_Total.BestFit();
                }
            }
            catch (Exception ex)
            {


            }
            //初始化显示视图
            InitGrand();
            //if (chk_BestFit.Checked)
            //{
            //    this.gdv_MpsMain.BestFitColumns();
            //}
        
        }
  

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (!txt_BIReportName.Text.StartsWith("Z"))
            {

                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
            else
            {
                this.GetMonitorList();
            }
        }

        private void GetMonitorList()
        {
            System.Data.DataTable dt = DbHelperSQL.Query("EXEC sp_BIReport_MaterialStatus '" + txt_BIReportName.Text + "'").Tables[0];
            if (dt.Rows.Count > 0)
            {
                txtFileName.Text = dt.Rows[0]["BIName"].ToString() + ".xlsx";
                txt_BIReportName.Text = dt.Rows[0]["BIName"].ToString();
            }
            this.gdv_MonitorList.Columns.Clear();
            this.gdc_MasterDataMonitor.DataSource = dt;
            this.gdv_MonitorList.BestFitColumns();
            this.xtraTabControl1.SelectedTabPage = this.xtraTabPage6;
        }

        private void InitGrand()
        {
            foreach (DevExpress.XtraGrid.Views.BandedGrid.GridBand item in this.gdv_MpsMain.Bands)
            {
                if (item.Name == "gridBand_Procurement" || item.Name == gridBand_basic.Name || item.Name == gridBand_PEInfo.Name)
                {
                    item.Visible = true;
                }
                else
                {
                    item.Visible = chk_OnlyForPOView.Checked;
                }

                if (chk_FIN.Checked)
                {

                    if (item.Name == "gridBand_templateofFIN")
                    {
                        item.Visible = true;
                    }
                    else
                    {
                        item.Visible = false;
                    }
                }
            }

            
        }

        public enum SAP_MM_P
        {
            NONE,
            PO,
            PE,
            ALL,
            PL,
            GC,
            SAPUpload,
            FIN,
            SYCHN
        }


        private void gdv_MpsMain_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }
        bool boolCopy = false;
        private void gdv_MpsMain_KeyUp(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void frmStatusMonitor_JobMatReq_Load(object sender, EventArgs e)
        {
            CFunctionUtility.InitGridViewSetColumnReadOnly(this.gdv_MpsMain, true);
            txtUserName.Text = Commoner.UseName.Trim();
            this.btn_SAPupload.Enabled = false;
            this.txtUpload_GC.Enabled = false;
            this.txtUpload_GY.Enabled = false;
            this.txtUpload_PO.Enabled = false;
            this.txtUpload_PL.Enabled = false;
            this.btn_Extending_1.Enabled = false;
            this.btn_Extending_2.Enabled = false;
            this.btnUpload_prodhrchy.Enabled = false;
            this.btnRegCN.Enabled = false;
            btn_FinishBOM.Enabled = false;
            this.btn_ProdOrderStatus.Enabled = false;
            this.btn_ProdOrderStatus_Clsd.Enabled = false;
            this.btn_SPN.Enabled = false;
            this.btn_SPY.Enabled = false;
            this.btn_Var1.Enabled = false;
            this.btn_Var2.Enabled = false;
            this.sb_uploadMRP.Enabled = false;
            this.btnPriceUploadForMissingPrice.Enabled = false;
            this.btn_FINRegist.Enabled = false;
            this.btn_Upload_F30.Enabled = false;
            if (CFunctionUtility.IsSysAdmin())
            {
                this.btn_SAPupload.Enabled = true;
                this.txtUpload_GC.Enabled = true;
                this.txtUpload_GY.Enabled = true;
                this.txtUpload_PL.Enabled = true;
                this.txtUpload_PO.Enabled = true;
                this.bandedGridColumn_del.Visible = true;
                this.bandedGridColumn_del.OptionsColumn.AllowEdit = true;
                this.btn_Extending_1.Enabled = true;
                this.btn_Extending_2.Enabled = true;
                this.btn_ProdOrderStatus.Enabled = true;
                this.btn_ProdOrderStatus_Clsd.Enabled = true;
                this.btn_SPN.Enabled = true;
                this.btn_SPY.Enabled = true;
                this.btn_Var1.Enabled = true;
                this.btn_Var2.Enabled = true;
                this.btnAdminDeleteSAPList.Enabled = true;
                btnAdminDeleteSAPList.Visible = true;
                this.sb_uploadMRP.Enabled = true;
                this.btnPriceUploadForMissingPrice.Enabled = true;
                this.btn_Upload_F30.Enabled = true;
            }
            else
            {
                this.bandedGridColumn_del.Visible = false;
                btnAdminDeleteSAPList.Visible = false;
            }
            if (AccessType == SAP_MM_P.PE) { this.txtUpload_GY.Enabled = true; btn_FinishBOM.Enabled = true; }
            if (AccessType == SAP_MM_P.PL)
            {
                this.txtUpload_PL.Enabled = true;
                this.btn_ProdOrderStatus.Enabled = true;
                this.btn_ProdOrderStatus_Clsd.Enabled = true;
                this.btn_Upload_F30.Enabled = true;
            }
            if (AccessType == SAP_MM_P.PO)
            {
                this.txtUpload_PO.Enabled = true;
                this.btnPriceUploadForMissingPrice.Enabled = true;
                this.sb_uploadMRP.Enabled = true;
                if (CFunctionUtility.IsSysAdmin())
                {
                    txtUserName.Text = "Dorothy.He";

                }
                else
                {
                }
              

            }



            if (Commoner.UserCode.Trim() == "A01017"||CFunctionUtility.IsSysAdmin())
            {
                btn_FINRegist.Enabled = true;
            }
            if (AccessType == SAP_MM_P.GC)
            {
                this.txtUpload_GC.Enabled = true; bandedGridColumn_PH.OptionsColumn.AllowEdit = true; bandedGridColumn_ProHrchySave.OptionsColumn.AllowEdit = true; this.bandedGridColumn_CNDesc.OptionsColumn.AllowEdit = true;
                this.btnUpload_prodhrchy.Enabled = true;

            }
            if (AccessType == SAP_MM_P.SAPUpload)
            {
                this.btn_SAPupload.Enabled = true;
                this.btn_Extending_1.Enabled = true;
                this.btn_Extending_2.Enabled = true;
                this.btn_ProdOrderStatus.Enabled = true;
                this.btn_ProdOrderStatus_Clsd.Enabled = true;
                if (CFunctionUtility.IsSysAdmin())
                {
                    this.txtUserName.Text = "王迎娣";
                }
                btnRegCN.Enabled = true;
            }


            foreach (DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn item in this.gdv_MpsMain.Columns)
            {
                item.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            }

            foreach (DevExpress.XtraGrid.Views.BandedGrid.GridBand item in this.gdv_MpsMain.Bands)
            {
                item.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            }


            btn_DeleteMARA.Enabled = CFunctionUtility.IsSysAdmin();
            btn_DeleteMARC.Enabled = CFunctionUtility.IsSysAdmin();

            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "ActiveStatus", "X", Color.Yellow);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "EditStatus", "Y", Color.Yellow);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "IsMissPOview", "Y", Color.Red);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "NeedToSynch", "Y", Color.Pink);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "T4SStatus", "-", Color.Aqua);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "SendToPOFlag", "-", Color.Tomato, false);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "ProdOrderStatus", "OPEN", Color.Purple, false);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "BOMAndRoutingStatus", "Y", Color.YellowGreen, false);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "SpecialFlag", "Y", Color.Yellow, false);
            //
            if (!CFunctionUtility.IsSysAdmin())
            {
                this.导出汇总ToolStripMenuItem.Visible = false;
                chk_CurrentStatus.Checked = true;

            }
            ///不是管理员不显示
            if (!CFunctionUtility.IsSysAdmin())
            {
                this.txtUserName.Visible = false;
                this.txt_var.Visible = false;
            }
            else
            {
                this.txtUserName.Visible = true;
                this.txt_var.Visible = true;
            }


            this.bandedGridColumn_Log.OptionsColumn.AllowEdit = true;

            this.InitWCGLookupList();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog opf = new SaveFileDialog();
            opf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\1 Data Download\\";
            opf.FileName = txtFileName.Text;
            if (opf.ShowDialog() == DialogResult.OK)
            {
                string fileName = opf.FileName;
                if (!opf.FileName.EndsWith("xlsx"))
                {
                    fileName = fileName + ".xlsx";
                }
                this.gdv_MpsMain.OptionsPrint.AutoWidth = false;

                if (chk_FIN.Checked)
                {
                    this.gdv_MpsMain.ExportToXlsx(fileName, new DevExpress.XtraPrinting.XlsxExportOptions() { SheetName = "ZFI_MATPUPLOAD" });
                }
                else
                {
                    this.gdv_MpsMain.ExportToXlsx(fileName, new DevExpress.XtraPrinting.XlsxExportOptions() { SheetName = "Sheet1" });
                }
            }
        }
        List<SAPItemQueryInfo> LstSAPUploadList = new List<SAPItemQueryInfo>();
        private void txtWorkOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (!CFunctionUtility.IsSysAdmin() && true)
            {
                frmPVSelect newform = new frmPVSelect();
                newform.TFormName = "工作令选择";
                newform.TstrTable = "cv_SO_WorkOrderMaster";
                newform.TSetMulRows = false;
                newform.TstrTitle = "WorkOrderDesc,工作令;ItemCode,物料号;ItemDrawingNumber,物料图号;ItemName,物料名称;ItemDescription,物料描述;OrderNumber,销售订单;OrderLine,订单行";
                newform.TSelFields = "WorkOrderDesc,工作令;ItemCode,物料号;ItemDrawingNumber,物料图号;ItemName,物料名称;ItemDescription,物料描述;OrderNumber,销售订单;OrderLine,订单行;Qty,数量;ItemCategory,物料性质";
                newform.TSpecialWhere = " And ItemCategory='M'";
                newform.TOrderBY = " Order by WorkOrderDesc";
                newform.TShowDetail = true;
                newform.ShowDialog();
                if (newform.TDataRow != null)
                {
                    string rtn = string.Empty;
                    foreach (DataRow row in newform.TDataRows)
                    {
                        if (rtn == "")
                        {
                            rtn = row["WorkOrderDesc"].ToString().Trim();
                        }
                        else
                        {
                            rtn += "," + row["WorkOrderDesc"].ToString().Trim();
                        }
                    }
                    //txt_ItemCode.Text = CommonHandle.TransRange(rtn);
                }
            }
            else
            {
                StringBuilder sb_WorkOrder = new StringBuilder();
                LstSAPUploadList.Clear();

                OpenFileDialog opf = new OpenFileDialog();
                if (opf.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                txtPath.Text = opf.FileName;

                try
                {
                    if (!string.IsNullOrEmpty(txtPath.Text))
                    {
                        System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                        List<string> LstSQL = new List<string>();
                        for (int i = 0; i < dt_excel.Rows.Count; i++)
                        {
                            string strItemCode = "";
                            string XH = "";
                            strItemCode = dt_excel.Rows[i][0].ToString();
                            //XH = dt_excel.Rows[i][0].ToString(); 
                            if (!string.IsNullOrEmpty(strItemCode))
                            {

                                sb_WorkOrder.AppendFormat("{0},", strItemCode);
                            }
                        }



                    }
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    if (sb_WorkOrder.Length > 1)
                    {
                        //  txtWorkOrder.Text = sb_WorkOrder.Remove(sb_WorkOrder.Length - 1, 1).ToString();
                    }
                }
            }
        }

        private void gdv_MpsMain_CustomDrawRowIndicator_1(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }

        private void gdv_MpsMain_KeyUp_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void gdv_MpsMain_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            DataRow dr = gdv_MpsMain.GetDataRow(e.RowHandle);
            // if (e.Column.FieldName == "ProductionQty")
            //{
            //    if (decimal.Parse(dr["OrderQty"].ToString()) == decimal.Parse(dr["ProductionQty"].ToString()))
            //    {
            //        e.Appearance.BackColor = Color.YellowGreen;
            //    }
            //}
            // if (e.Column.FieldName == "DeliveriedQty")
            // {
            //     if (decimal.Parse(dr["OrderQty"].ToString()) == decimal.Parse(dr["DeliveriedQty"].ToString()))
            //     {
            //         e.Appearance.BackColor = Color.YellowGreen;
            //     }
            // }
        }

        private void chkIsShowOperator_CheckedChanged(object sender, EventArgs e)
        {

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gdv_MpsMain.Columns)
            {

            }

        }

        private void txtItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("GC"))) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                DOUploadMaterial_GC();
            }
        }

        private void DOUploadMaterial(string UploadType)
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();
            if (UploadType != "CG" && UploadType != "GY")
            {
                OpenFileDialog opf = new OpenFileDialog();
                if (opf.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                txtPath.Text = opf.FileName;
            }

            try
            {
                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 1; i < dt_excel.Rows.Count; i++)
                    {
                        string _Plant = "CN02";
                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _Material_Description = dt_excel.Rows[i][1].ToString();
                        string _PriceUnit = "";
                        string _Unit_Issue = "EA";
                        string _Currency = "RMB";
                        string _Price = "";
                        string _MaterialType = "";
                        string _MaterialGroup = "";
                        string _LastChange = "";
                        string _PurchasingGroup = "";
                        string _ABC = "";
                        string _MRP_Type = "";
                        string _Procurement_Type = dt_excel.Rows[i][2].ToString();
                        string _ValCl = "";
                        string _PriceControl = "";
                        string _CreatedBy = "";
                        string _ValuationType = "";
                        string _CreateDate = "";
                        string _Special_Procurement_Type = dt_excel.Rows[i][3].ToString();
                        string _MRP_Controller = "";
                        string _Planned_Delivery_Days = "";
                        string _Monetary_Unit = "";
                        string _Purchasing_Cost = "";
                        string _Backflush = "";
                        string _GR_Processing_Time = "";
                        string _Reorder_Point = "";
                        string _Lot_Size = "";
                        string _Maximum_Stock_Level = "";
                        string _Safety_Stock = "";
                        string _Minimum_Lot_Size = "";
                        string _Strategy_Group = "";
                        string _Individual_Collective_Requ = "";
                        string _Scheduling_Margin = "";
                        string _Indicator_Backflush = "";
                        string _In_House_Production_Time = "";
                        string _Profit_Center = "";
                        string _InspectionFlag = "";
                        string _MRP_Controller_PL = dt_excel.Rows[i][5].ToString();
                        string _Serial_Number = dt_excel.Rows[i][4].ToString();
                        string _PurchasingCategory = dt_excel.Rows[i][6].ToString();
                        if (!string.IsNullOrEmpty(_Material_Number))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description.Replace("'", "''"),
                                CreatedBy = Commoner.UseName.Trim(),
                                Purchasing_Cost = _Purchasing_Cost,
                                PurchasingGroup = _PurchasingGroup,
                                MRP_Type = _MRP_Type,
                                MRP_Controller = _MRP_Controller,
                                Procurement_Type = _Procurement_Type,
                                Special_Procurement_Type = _Special_Procurement_Type,
                                Serial_Number = _Serial_Number,
                                Upload_Type = UploadType,
                                Backflush = _Backflush,
                                MRP_Controller_PL = _MRP_Controller_PL,
                                PurchasingCategory = _PurchasingCategory
                            });
                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();
                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {
                        //查询时候，不进行数据处理
                        if (UploadType != "Query")
                        {
                            LstSQL.Add(string.Format("exec SP_Upload_SAPMaterialToMonitor @MaterialNumber='{0}',@Description='{1}',@Procurement_Type='{2}',@Special_Procurement_Type='{3}',@UploadType='{4}',@CreateUser='{5}',@SN='{6}',@MRP_Controller_PL='{7}',@Backflush='{8}',@PurchasingCategory='{9}'",
                                item.Material_Number,
                                item.Material_Description,
                                item.Procurement_Type,
                                item.Special_Procurement_Type,
                                item.Upload_Type,
                                txtUserName.Text,
                                item.Serial_Number,
                                item.MRP_Controller_PL,
                                item.Backflush,
                                item.PurchasingCategory
                                ));
                        }
                        sbm.AppendFormat("{0},", item.Material_Number);
                    }
                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }
                //查询模式不进行数据处理
                if (UploadType != "Query")
                {
                    if (MessageBox.Show("确定要进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        DbHelperSQL.ExecuteSqlTran(LstSQL);
                        MessageBox.Show("上传完毕，请核实!");
                    }
                }
                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }
        /// <summary>
        /// 工程上传新物料
        /// </summary>
        private void DOUploadMaterial_GC()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();


            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 1; i < dt_excel.Rows.Count; i++)
                    {
                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _Material_Description = dt_excel.Rows[i][1].ToString();
                        string _Owner = dt_excel.Rows[i][2].ToString();
                        string _CN_Description = dt_excel.Rows[i][3].ToString();
                        if (!string.IsNullOrEmpty(_Material_Number))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description.Replace("'", "''"),
                                CreatedBy = Commoner.UseName.Trim(),
                                CN_Description = _CN_Description,
                                Owner = _Owner,
                            });
                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();
                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {

                        LstSQL.Add(string.Format("exec SP_Upload_SAPMaterialToMonitor_GC @MaterialNumber='{0}',@Description='{1}',@Owner='{2}',@CreateUser='{3}',@CN_Description='{4}'", item.Material_Number, item.Material_Description, item.Owner, txtUserName.Text, item.CN_Description.Replace("'", "''")));
                        sbm.AppendFormat("{0},", item.Material_Number);
                    }
                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }

                if (MessageBox.Show("确定要进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }

                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }

        /// <summary>
        /// 上传产品层级
        /// </summary>
        private void DOUploadMaterial_GC_ProdHierarchy()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();


            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {
                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _Material_Description = dt_excel.Rows[i][1].ToString();
                        string _Owner = dt_excel.Rows[i][2].ToString();
                        string _CN_Description = dt_excel.Rows[i][3].ToString();
                        string __ProductHierarchyName = dt_excel.Rows[i][4].ToString();
                        string _ProductHierarchy = dt_excel.Rows[i][5].ToString();

                        if (!string.IsNullOrEmpty(_Material_Number) && !string.IsNullOrEmpty(_ProductHierarchy))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description.Replace("'", "''"),
                                CreatedBy = Commoner.UseName.Trim(),
                                CN_Description = _CN_Description.Trim(),
                                Owner = _Owner,
                                ProductHierarchy = _ProductHierarchy.Trim(),
                                ProductHierarchyName = __ProductHierarchyName.Trim(),
                                Uploaded_By = Commoner.UseName.Trim(),
                            });
                        }
                    }
                }

                this.gdc_prodHrchy.DataSource = LstSAPUploadList;

                this.gdc_prodHrchy.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();
                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {

                        LstSQL.Add(string.Format("exec SP_Upload_SAPMaterialToMonitor_GC_ProdHierarchy @MaterialNumber='{0}',@CreateUser='{1}',@CN_Description='{2}',@ProdHierarchy='{3}'", item.Material_Number, txtUserName.Text, item.CN_Description.Replace("'", "''"), item.ProductHierarchy));
                        sbm.AppendFormat("{0},", item.Material_Number);
                    }
                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }
                if (MessageBox.Show("确定要进行【上传产品层级】数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }

                this.GetDataFromSystem(SAP_MM_P.ALL);
                this.xtraTabControl1.SelectedTabPageIndex = 0;
            }
        }

        /// <summary>
        /// PCN NO 
        /// </summary>
        private void DOUploadMaterial_GC_PCN_NO()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();


            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {
                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _Material_Description = dt_excel.Rows[i][1].ToString();
                        string _PCNNO = dt_excel.Rows[i][2].ToString();
                        if (!string.IsNullOrEmpty(_Material_Number) && !string.IsNullOrEmpty(_PCNNO))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description.Replace("'", "''"),
                                CreatedBy = Commoner.UseName.Trim(),
                                PCN_NO = _PCNNO,
                                Uploaded_By = Commoner.UseName.Trim(),
                            });
                        }
                    }
                }

                this.gdc_prodHrchy.DataSource = LstSAPUploadList;

                this.gdc_prodHrchy.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();
                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {

                        LstSQL.Add(string.Format("exec SP_Upload_SAPMaterialToMonitor_GC_PCN_NO @MaterialNumber='{0}',@CreateUser='{1}',@PCN_NO='{2}'", item.Material_Number, txtUserName.Text, item.PCN_NO.Replace("'", "''").Trim()));
                        sbm.AppendFormat("{0},", item.Material_Number);
                    }
                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }
                if (MessageBox.Show("确定要进行【PCN NO】数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }

                this.GetDataFromSystem(SAP_MM_P.ALL);
                this.xtraTabControl1.SelectedTabPageIndex = 0;
            }
        }

        private void DOUploadMaterial_PO(string UploadType)
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();
            try
            {
                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 1; i < dt_excel.Rows.Count; i++)
                    {
                        string _Plant = "CN02";
                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _Material_Description = "";
                        string _PriceUnit = "";
                        string _Unit_Issue = "EA";
                        string _Currency = dt_excel.Rows[i][3].ToString();
                        string _Price = "";
                        string _MaterialType = "";
                        string _MaterialGroup = "";
                        string _LastChange = "";
                        string _PurchasingGroup = dt_excel.Rows[i][1].ToString();
                        string _ABC = "";
                        string _MRP_Type = dt_excel.Rows[i][5].ToString();
                        string _Procurement_Type = "";
                        string _ValCl = "";
                        string _PriceControl = "";
                        string _CreatedBy = "";
                        string _ValuationType = "";
                        string _CreateDate = "";
                        string _Special_Procurement_Type = "";
                        string _MRP_Controller = dt_excel.Rows[i][6].ToString();
                        string _Planned_Delivery_Days = dt_excel.Rows[i][4].ToString();
                        string _Monetary_Unit = "";
                        string _Purchasing_Cost = dt_excel.Rows[i][2].ToString().Trim();
                        string _Backflush = "";
                        string _GR_Processing_Time = "";
                        string _Reorder_Point = dt_excel.Rows[i][13].ToString();
                        string _Lot_Size = dt_excel.Rows[i][9].ToString();
                        string _Maximum_Stock_Level = dt_excel.Rows[i][10].ToString();
                        string _Safety_Stock = dt_excel.Rows[i][12].ToString();
                        string _Minimum_Lot_Size = dt_excel.Rows[i][11].ToString();
                        string _Strategy_Group = dt_excel.Rows[i][7].ToString();
                        string _Individual_Collective_Requ = dt_excel.Rows[i][8].ToString();
                        string _Scheduling_Margin = "";
                        string _Indicator_Backflush = "";
                        string _In_House_Production_Time = "";
                        string _Profit_Center = "";
                        string _InspectionFlag = "";
                        string _Serial_Number = "";
                        string _ProcumentOwner = dt_excel.Rows[i][14].ToString();
                        string _Special_Procurement_Type_PO = dt_excel.Rows[i][14].ToString();
                        if (!string.IsNullOrEmpty(_Material_Number))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description,
                                CreatedBy = Commoner.UseName.Trim(),
                                Purchasing_Cost = _Purchasing_Cost.Trim(),
                                PurchasingGroup = _PurchasingGroup.Trim(),
                                MRP_Type = _MRP_Type.Trim(),
                                MRP_Controller = _MRP_Controller.Trim(),
                                Procurement_Type = _Procurement_Type,
                                Special_Procurement_Type = _Special_Procurement_Type.Trim(),
                                Serial_Number = _Serial_Number.Trim(),
                                Upload_Type = UploadType.Trim(),
                                Currency = _Currency.Trim(),
                                Individual_Collective_Requ = _Individual_Collective_Requ.Trim(),
                                MaterialGroup = _MaterialGroup.Trim(),
                                Monetary_Unit = _Monetary_Unit.Trim(),
                                Planned_Delivery_Days = _Planned_Delivery_Days.Trim(),
                                Strategy_Group = _Strategy_Group.Trim(),
                                Lot_Size = _Lot_Size.Trim(),
                                Maximum_Stock_Level = _Maximum_Stock_Level.Trim(),
                                Minimum_Lot_Size = _Minimum_Lot_Size.Trim(),
                                Safety_Stock = _Safety_Stock.Trim(),
                                Reorder_Point = _Reorder_Point.Trim(),
                                ProcurementOwner = _ProcumentOwner.Trim(),
                                Special_Procurement_Type_PO = _Special_Procurement_Type_PO

                            });
                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();

                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {
                        StringBuilder sbSql_ex = new StringBuilder();
                        sbSql_ex.Append("	EXEC  SP_Upload_SAPMaterialToMonitor_PR  ");
                        sbSql_ex.AppendFormat("	@MaterialNumber='{0}',  ", item.Material_Number);
                        sbSql_ex.AppendFormat("	@PurchasingGroup='{0}', ", item.PurchasingGroup);
                        sbSql_ex.AppendFormat("	@Purchasing_Cost='{0}',  ", item.Purchasing_Cost);
                        sbSql_ex.AppendFormat("	@Currency='{0}',  ", item.Currency);
                        sbSql_ex.AppendFormat("	@Planned_Delivery_Days='{0}',  ", item.Planned_Delivery_Days);
                        sbSql_ex.AppendFormat("	@MRP_Type='{0}', ", item.MRP_Type);
                        sbSql_ex.AppendFormat("	@MRP_Controller='{0}',  ", item.MRP_Controller);
                        sbSql_ex.AppendFormat("	@Strategy_Group='{0}',  ", item.Strategy_Group);
                        sbSql_ex.AppendFormat("	@Individual_Collective_Requ='{0}',  ", item.Individual_Collective_Requ);
                        sbSql_ex.AppendFormat("  @Lot_Size ='{0}', ", item.Lot_Size);
                        sbSql_ex.AppendFormat("  @Maximum_Stock_Level ='{0}', ", item.Maximum_Stock_Level);
                        sbSql_ex.AppendFormat("  @Minimum_Lot_Size ='{0}', ", item.Minimum_Lot_Size);
                        sbSql_ex.AppendFormat("  @Safety_Stock  = '{0}' , ", item.Safety_Stock);
                        sbSql_ex.AppendFormat("  @Reorder_Point  ='{0}', ", item.Reorder_Point);
                        sbSql_ex.AppendFormat("	@UploadType='{0}', ", "PO");
                        sbSql_ex.AppendFormat("	@Special_Procurement_Type_PO='{0}', ", item.Special_Procurement_Type_PO.Trim());
                        sbSql_ex.AppendFormat("	@CreateUser='{0}' ", txtUserName.Text);


                        LstSQL.Add(sbSql_ex.ToString());
                        sbm.AppendFormat("{0},", item.Material_Number);
                    }

                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }
                if (MessageBox.Show("确定要【采购】进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }
                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }


        private void DOUploadMaterial_PO_FullVersion(string UploadType)
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();
            try
            {
                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 1; i < dt_excel.Rows.Count; i++)
                    {
                        string _Plant = "CN02";
                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _Material_Description = "";
                        string _PriceUnit = "";
                        string _Unit_Issue = "EA";
                        string _Currency = dt_excel.Rows[i][10].ToString();
                        string _Price = "";
                        string _MaterialType = "";
                        string _MaterialGroup = "";
                        string _LastChange = "";
                        string _PurchasingGroup = dt_excel.Rows[i][8].ToString();
                        string _ABC = "";
                        string _MRP_Type = dt_excel.Rows[i][12].ToString();
                        string _Procurement_Type = "";
                        string _ValCl = "";
                        string _PriceControl = "";
                        string _CreatedBy = "";
                        string _ValuationType = "";
                        string _CreateDate = "";
                        string _Special_Procurement_Type = "";
                        string _MRP_Controller = dt_excel.Rows[i][13].ToString();
                        string _Planned_Delivery_Days = dt_excel.Rows[i][11].ToString().ToLower().Replace("days", "").Trim();
                        string _Monetary_Unit = "";
                        string _Purchasing_Cost = dt_excel.Rows[i][9].ToString().Trim();
                        string _Backflush = "";
                        string _GR_Processing_Time = "";
                        string _Reorder_Point = dt_excel.Rows[i][20].ToString();
                        string _Lot_Size = dt_excel.Rows[i][16].ToString();
                        string _Maximum_Stock_Level = dt_excel.Rows[i][17].ToString();
                        string _Safety_Stock = dt_excel.Rows[i][19].ToString();
                        string _Minimum_Lot_Size = dt_excel.Rows[i][18].ToString();
                        string _Strategy_Group = dt_excel.Rows[i][14].ToString();
                        string _Individual_Collective_Requ = dt_excel.Rows[i][15].ToString();
                        string _Scheduling_Margin = "";
                        string _Indicator_Backflush = "";
                        string _In_House_Production_Time = "";
                        string _Profit_Center = "";
                        string _InspectionFlag = "";
                        string _Serial_Number = "";
                        string _ProcumentOwner = dt_excel.Rows[i][7].ToString();
                        string _Special_Procurement_Type_PO = dt_excel.Rows[i][7].ToString();
                        if (!string.IsNullOrEmpty(_Material_Number))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description,
                                CreatedBy = Commoner.UseName.Trim(),
                                Purchasing_Cost = _Purchasing_Cost.Trim(),
                                PurchasingGroup = _PurchasingGroup.Trim(),
                                MRP_Type = _MRP_Type.Trim(),
                                MRP_Controller = _MRP_Controller.Trim(),
                                Procurement_Type = _Procurement_Type,
                                Special_Procurement_Type = _Special_Procurement_Type.Trim(),
                                Serial_Number = _Serial_Number.Trim(),
                                Upload_Type = UploadType.Trim(),
                                Currency = _Currency.Trim(),
                                Individual_Collective_Requ = _Individual_Collective_Requ.Trim(),
                                MaterialGroup = _MaterialGroup.Trim(),
                                Monetary_Unit = _Monetary_Unit.Trim(),
                                Planned_Delivery_Days = _Planned_Delivery_Days.Trim(),
                                Strategy_Group = _Strategy_Group.Trim(),
                                Lot_Size = _Lot_Size.Trim(),
                                Maximum_Stock_Level = _Maximum_Stock_Level.Trim(),
                                Minimum_Lot_Size = _Minimum_Lot_Size.Trim(),
                                Safety_Stock = _Safety_Stock.Trim(),
                                Reorder_Point = _Reorder_Point.Trim(),
                                ProcurementOwner = _ProcumentOwner.Trim(),
                                 Special_Procurement_Type_PO=_Special_Procurement_Type_PO,

                            });
                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();

                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {
                        StringBuilder sbSql_ex = new StringBuilder();
                        sbSql_ex.Append("	EXEC  SP_Upload_SAPMaterialToMonitor_PR  ");
                        sbSql_ex.AppendFormat("	@MaterialNumber='{0}',  ", item.Material_Number);
                        sbSql_ex.AppendFormat("	@PurchasingGroup='{0}', ", item.PurchasingGroup);
                        sbSql_ex.AppendFormat("	@Purchasing_Cost='{0}',  ", item.Purchasing_Cost);
                        sbSql_ex.AppendFormat("	@Currency='{0}',  ", item.Currency);
                        sbSql_ex.AppendFormat("	@Planned_Delivery_Days='{0}',  ", item.Planned_Delivery_Days);
                        sbSql_ex.AppendFormat("	@MRP_Type='{0}', ", item.MRP_Type);
                        sbSql_ex.AppendFormat("	@MRP_Controller='{0}',  ", item.MRP_Controller);
                        sbSql_ex.AppendFormat("	@Strategy_Group='{0}',  ", item.Strategy_Group);
                        sbSql_ex.AppendFormat("	@Individual_Collective_Requ='{0}',  ", item.Individual_Collective_Requ);
                        sbSql_ex.AppendFormat("  @Lot_Size ='{0}', ", item.Lot_Size);
                        sbSql_ex.AppendFormat("  @Maximum_Stock_Level ='{0}', ", item.Maximum_Stock_Level);
                        sbSql_ex.AppendFormat("  @Minimum_Lot_Size ='{0}', ", item.Minimum_Lot_Size);
                        sbSql_ex.AppendFormat("  @Safety_Stock  = '{0}' , ", item.Safety_Stock);
                        sbSql_ex.AppendFormat("  @Reorder_Point  ='{0}', ", item.Reorder_Point);
                        sbSql_ex.AppendFormat("	@UploadType='{0}', ", "PO");
                        sbSql_ex.AppendFormat("	@Special_Procurement_Type_PO='{0}', ", item.Special_Procurement_Type_PO.Trim());
                        sbSql_ex.AppendFormat("	@CreateUser='{0}' ", txtUserName.Text);
                        LstSQL.Add(sbSql_ex.ToString());
                        sbm.AppendFormat("{0},", item.Material_Number);
                    }

                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }
                if (MessageBox.Show("确定要【采购】进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }
                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }

        private void btnPE_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem(SAP_MM_P.PE);
        }

        private void btnPO_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem(SAP_MM_P.PO);
        }



        private void xtraTabPage1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btn_GY_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("GY"))) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                this.DOUploadMaterial("GY");
            }
        }

        private void btn_POUpload_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\2 Data Upload\\";
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("PO")) && !txtPath.Text.Contains("S3")) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                if (!txtPath.Text.Contains("S3"))
                {
                    this.DOUploadMaterial_PO("PO");
                }
                else
                {
                    this.DOUploadMaterial_PO_FullVersion("PO");
                }
            }
        }

        private void btn_SAPupload_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            this.DOUploadMaterial("SAP");
        }

        private void txt_MaterialNumber_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            this.DOUploadMaterial("Query");
        }

        private void repositoryItemSpinEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void repositoryItemButtonEdit_Delete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (MessageBox.Show("确定删除/恢复吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                DataRow dr = this.gdv_MpsMain.GetFocusedDataRow();
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append("UPDATE sim SET sim.ActiveStatus=CASE isnull(sim.ActiveStatus,'') ");
                sbSql.Append("WHEN '' THEN 'X' ");
                sbSql.Append("ELSE '' END  , ");
                sbSql.Append("Del_Date=GETDATE() ");
                sbSql.Append("FROM SAP_ItemMaster sim ");
                sbSql.AppendFormat("WHERE sim.Oid='{0}' ", dr["Oid"].ToString());
                DbHelperSQL.ExecuteSql(sbSql.ToString());
                MessageBox.Show("处理完毕", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }

        private void txtFileName_TextChanged(object sender, EventArgs e)
        {

        }

        private void 导出明细ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CFunctionUtility.ExportToExcel(this.bandedGridView1
                                          , "KPI" + DateTime.Now.ToString("yyyMMdd")
                                          , true);
        }

        private void 导出汇总ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CFunctionUtility.ExportToExcel(this.bandedGridView2);
        }

        private void btn_ExtendFinished_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DOUploadMaterial("SAP2");
        }

        /// <summary>
        /// 获得模板SN
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public string GetSNByType(string typeName)
        {
            StringBuilder sbSql_sn = new StringBuilder();
            sbSql_sn.Append("SELECT top 1   z.SN  FROM SAP_Template_Version z ");
            sbSql_sn.AppendFormat("WHERE z.TypeName='{0}' ", typeName);
            return DbHelperSQL.Query(sbSql_sn.ToString()).Tables[0].Rows[0]["SN"].ToString();
        }

        private void InitWCGLookupList()
        {

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT sph.[GROUP], sph.Main_Group, sph.Subgroup, sph.Prod_Hierarchy, ");
            sbSql.Append("       sph.Prod_Hierarchy_Code ");
            sbSql.Append("  FROM SAP_ProductHierarchy sph ");
            sbSql.Append("ORDER BY  sph.Prod_Hierarchy_Code ");

            DataSet dstemp = DbHelperSQL.Query(sbSql.ToString());

            if (dstemp != null && dstemp.Tables.Count > 0)
            {


                this.repositoryItemLookUpEdit_PrdHrchy.DataSource = dstemp.Tables[0];


                this.repositoryItemLookUpEdit_PrdHrchy.DisplayMember = "Prod_Hierarchy";
                this.repositoryItemLookUpEdit_PrdHrchy.ValueMember = "Prod_Hierarchy_Code";


            }

        }

        private void repositoryItemButtonEdit_ProHrchySave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow dr = this.gdv_MpsMain.GetFocusedDataRow();
            if (dr != null)
            {
                string strProductHierarchy = dr["ProductHierarchy"].ToString();
                string strCN_Description = dr["CN_Description"].ToString();
                if (string.IsNullOrEmpty(strCN_Description.Trim()))
                {
                    MessageBox.Show("亲爱的同事，请在填写产品层级的同时，也将【中文描述】一起填写," + Environment.NewLine + "这样有利于工人识别部件,谢谢", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (SaveProductHierarchy(dr["Material_Number"].ToString(), strProductHierarchy, strCN_Description))
                {
                    dr["EditStatus"] = "Y";
                    this.gdc_MpsMain.RefreshDataSource();
                }
            }
        }

        private bool SaveProductHierarchy(string Material_Number, string ProductHierarchy, string CN_Description)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat(" UPDATE sim SET sim.ProductHierarchy = '{0}' ,", ProductHierarchy);
            sbSql.AppendFormat(" GC_P_User='{0}',", txtUserName.Text);
            sbSql.AppendFormat(" CN_Description='{0}',", CN_Description.Replace("'", "''"));
            sbSql.AppendFormat(" GC_P_Date=case  when GC_P_Date IS NULL then  getdate() else GC_P_Date end");
            sbSql.AppendFormat(" FROM SAP_ItemMaster sim WHERE sim.Material_Number='{0}' ", Material_Number);
            return DbHelperSQL.ExecuteSql(sbSql.ToString()) > 0;
        }

        private void 导入ViewResultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            DOUploadMaterial_ViewStatus();
        }


        private void DOUploadMaterial_ViewStatus()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();

            List<SAP_ViewStatus> LstView = new List<SAP_ViewStatus>();

            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {

                        string _Material = dt_excel.Rows[i][0].ToString();
                        string _BASIC_VIEW = dt_excel.Rows[i][1].ToString();
                        string _SALES = dt_excel.Rows[i][2].ToString();
                        string _PURCHASING = dt_excel.Rows[i][3].ToString();
                        string _WORK_SCHEDULING = dt_excel.Rows[i][4].ToString();
                        string _QUALITY_MANAGEMENT = dt_excel.Rows[i][5].ToString();
                        string _ACCOUNTING = dt_excel.Rows[i][6].ToString();
                        string _COSTING = dt_excel.Rows[i][7].ToString();
                        string _MRP = dt_excel.Rows[i][8].ToString();
                        string _PLANT_STORAGE_LOC = dt_excel.Rows[i][9].ToString();
                        string _PROCUREMENT_TYPE = dt_excel.Rows[i][10].ToString();
                        string _MATERIAL_PLANT_STATUS = dt_excel.Rows[i][11].ToString();
                        string _COST_PRICE = dt_excel.Rows[i][12].ToString();
                        string _Crcy = dt_excel.Rows[i][13].ToString();

                        string _IN_HOUSE_TIME = dt_excel.Rows[i][14].ToString();
                        string _PLAN_DEL_TIME = dt_excel.Rows[i][15].ToString();
                        string _MRP_TYPE = dt_excel.Rows[i][16].ToString();
                        string _STRATEGY_GROUP = dt_excel.Rows[i][17].ToString();
                        string _BOM_EXIT = dt_excel.Rows[i][18].ToString();

                        string _PRODUCT_HIERARCHY_S = dt_excel.Rows[i][19].ToString();
                        string _PRODUCT_HIERARCHY = dt_excel.Rows[i][20].ToString();
                        string _ENName = dt_excel.Rows[i][21].ToString();
                        string _CNName = dt_excel.Rows[i][22].ToString();


                        if (!string.IsNullOrEmpty(_Material))
                        {
                            LstView.Add(new SAP_ViewStatus
                            {
                                ACCOUNTING = _ACCOUNTING,
                                BASIC_VIEW = _BASIC_VIEW,
                                COST_PRICE = _COST_PRICE,
                                COSTING = _COSTING,
                                Crcy = _Crcy,
                                Material = _Material,
                                MATERIAL_PLANT_STATUS = _MATERIAL_PLANT_STATUS,
                                MRP = _MRP,
                                PLANT_STORAGE_LOC = _PLANT_STORAGE_LOC,
                                PROCUREMENT_TYPE = _PROCUREMENT_TYPE,
                                PURCHASING = _PURCHASING,
                                QUALITY_MANAGEMENT = _QUALITY_MANAGEMENT,
                                SALES = _SALES,
                                WORK_SCHEDULING = _WORK_SCHEDULING,
                                BOM_EXIT = _BOM_EXIT,
                                IN_HOUSE_TIME = _IN_HOUSE_TIME,
                                MRP_TYPE = _MRP_TYPE,
                                PLAN_DEL_TIME = _PLAN_DEL_TIME,
                                PRODUCT_HIERARCHY = _PRODUCT_HIERARCHY,
                                ROUTING_EXIT = "",
                                STRATEGY_GROUP = _STRATEGY_GROUP,
                                _CNName = _CNName.Replace("'", "''"),
                                _ENName = _ENName.Replace("'", "''"),
                                PRODUCT_HIERARCHY_S = _PRODUCT_HIERARCHY_S

                            });
                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstView.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();
                    foreach (SAP_ViewStatus item in LstView)
                    {
                        StringBuilder sbSql_v = new StringBuilder();
                        sbSql_v.Append("exec SP_Upload_SAPMaterialToMonitor_View  ");
                        sbSql_v.AppendFormat("@Material ='{0}', ", item.Material);
                        sbSql_v.AppendFormat("@BASIC_VIEW ='{0}', ", item.BASIC_VIEW);
                        sbSql_v.AppendFormat("@SALES ='{0}', ", item.SALES);
                        sbSql_v.AppendFormat("@PURCHASING ='{0}', ", item.PURCHASING);
                        sbSql_v.AppendFormat("@WORK_SCHEDULING ='{0}', ", item.WORK_SCHEDULING);
                        sbSql_v.AppendFormat("@QUALITY_MANAGEMENT  ='{0}', ", item.QUALITY_MANAGEMENT);
                        sbSql_v.AppendFormat("@ACCOUNTING ='{0}', ", item.ACCOUNTING);
                        sbSql_v.AppendFormat("@COSTING ='{0}', ", item.COSTING);
                        sbSql_v.AppendFormat("@MRP ='{0}', ", item.MRP);
                        sbSql_v.AppendFormat("@PLANT_STORAGE_LOC ='{0}', ", item.PLANT_STORAGE_LOC);
                        sbSql_v.AppendFormat("@PROCUREMENT_TYPE ='{0}', ", item.PROCUREMENT_TYPE);
                        sbSql_v.AppendFormat("@MATERIAL_PLANT_STATUS ='{0}', ", item.MATERIAL_PLANT_STATUS);
                        sbSql_v.AppendFormat("@COST_PRICE  ='{0}', ", item.COST_PRICE);
                        sbSql_v.AppendFormat("@Crcy ='{0}', ", item.Crcy);
                        sbSql_v.AppendFormat("@PRODUCT_HIERARCHY ='{0}', ", item.PRODUCT_HIERARCHY);
                        sbSql_v.AppendFormat("@IN_HOUSE_TIME ='{0}', ", item.IN_HOUSE_TIME);
                        sbSql_v.AppendFormat("@PLAN_DEL_TIME ='{0}', ", item.PLAN_DEL_TIME);
                        sbSql_v.AppendFormat("@MRP_TYPE ='{0}', ", item.MRP_TYPE);
                        sbSql_v.AppendFormat("@STRATEGY_GROUP ='{0}', ", item.STRATEGY_GROUP);
                        sbSql_v.AppendFormat("@BOM_EXIT ='{0}', ", item.BOM_EXIT);
                        sbSql_v.AppendFormat("@ROUTING_EXIT ='{0}', ", item.ROUTING_EXIT);
                        sbSql_v.AppendFormat("@V_ProdHierarchy_SALES ='{0}', ", item.PRODUCT_HIERARCHY_S);
                        sbSql_v.AppendFormat("@V_EN_NAME ='{0}', ", item._ENName);
                        sbSql_v.AppendFormat("@V_CN_NAME ='{0}' ", item._CNName);

                        LstSQL.Add(string.Format(sbSql_v.ToString()));
                        sbm.AppendFormat("{0},", item.Material);
                    }
                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }

                if (MessageBox.Show("确定要进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }

                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要进行BI分析数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                DbHelperSQL.ExecuteSql("exec sp_ExecuteBIAnalyzeForMasterData  ");
                MessageBox.Show("执行BI分析成功,可以通过【BI Name】来查看分析报表！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rch_MaterialList.Text);
            sb.Replace("\t\n", "|");
            sb.Replace("\n", "|");
            sb.Replace(" ", "");
            rch_MaterialList.Text = sb.ToString().Replace("|", ",");
            if (rch_MaterialList.Text.EndsWith(","))
            {
                rch_MaterialList.Text = rch_MaterialList.Text.Substring(0, sb.Length - 1);
            }
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            txt_MaterialNumber.Text = rch_MaterialList.Text;
        }

        private void btn_Extending_1_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("SAP", "第一阶段录入完成");
        }

        private void UploadSAPStatusOfProgress(string uploadType, string Msg)
        {
            List<string> LstSQL = new List<string>();

            foreach (string itemcode in txt_MaterialNumber.Text.Split(','))
            {
                string sbSql_v = string.Format(" exec sp_Upload_SAP_StatusOfProgress @MaterialNumber='{0}',@UploadType='{1}',@CreateUser='{2}',@Values='{3}' ", itemcode.ToUpper().Trim(), uploadType, txtUserName.Text.Trim(), txt_var.Text.Trim());
                LstSQL.Add(string.Format(sbSql_v.ToString()));
            }
            if (MessageBox.Show(string.Format("确定要进度完成【{0}】?", Msg), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                if (LstSQL.Count > 0)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                    this.GetDataFromSystem(SAP_MM_P.ALL);
                    this.xtraTabControl1.SelectedTabPageIndex = 0;
                }
                else
                {
                    MessageBox.Show("没有数据要进行登记");
                }
            }

        }

        private void btn_Extending_2_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("SAP2", "第二阶段录入完成，可以通知财务释放");
        }

        private void btnReverse_Click(object sender, EventArgs e)
        {
            StringBuilder sblst = new StringBuilder();
            foreach (string item in txt_MaterialNumber.Text.Split(','))
            {
                sblst.Append(item.Trim());
                sblst.AppendLine();
            }
            this.rch_MaterialList.Text = sblst.ToString();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.rch_MaterialList.Text = "";

        }

        private void chk_OnlyForPOView_CheckedChanged(object sender, EventArgs e)
        {
            InitGrand();
        }



        private void btn_NeedtoSynch_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("DELETE_MARA", "确定删除MARA吗?");
        }

        private void btn_FinishBOM_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("BOMRouting", "BOM and  Routing 完成吗?");
        }



        private void btnUpload_prodhrchy_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("GP"))) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                DOUploadMaterial_GC_ProdHierarchy();
            }
        }


        private void simpleButton3_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rch_MaterialList.Text);

            sb.Replace("\t\n", "|");
            sb.Replace("\t", "$");
            sb.Replace(" ", "");
            rch_PriceList.Text = "";
            decimal k = 0;
            List<PriceMappingList> LstPrice = new List<PriceMappingList>();

            foreach (string item in sb.ToString().Split('|'))
            {
                string m = item.Split('$')[0];

                if (item.Split('$').Length <= 1)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(m))
                {
                    continue;
                }
                rch_MaterialList.AppendText(m.Trim());
                rch_MaterialList.AppendText(Environment.NewLine);
                if (String.IsNullOrEmpty(item.Split('$')[1]))
                {
                    MessageBox.Show(string.Format("物料{0}，无中文描述，请修复", m), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                LstPrice.Add(new PriceMappingList() { Material = m, CN_Description = (item.Split('$')[1]), Price = -9999 });
            }
            
            this.gridControl_Price.DataSource = LstPrice;
            this.xtraTabControl1.SelectedTabPage = this.xtraTabPage7; 
            this.gridView_Price.BestFitColumns();

            Upload_CN_Desc(sender,e);



        }

        private void Upload_CN_Desc(object sender,EventArgs e)
        {
            List<PriceMappingList> L = this.gridView_Price.DataSource as List<PriceMappingList>;

            if (MessageBox.Show("确定中文描述上传吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {

                List<string> LstSQL = new List<string>();

                foreach (PriceMappingList itemcode in L)
                {
                    string sbSql_v = string.Format(" exec sp_Upload_SAP_StatusOfProgress @MaterialNumber='{0}',@UploadType='{1}',@CreateUser='{2}',@Values='{3}' ", itemcode.Material.ToUpper().Trim(), "UPLOAD_CNDESC", txtUserName.Text.Trim(), itemcode.CN_Description);
                    LstSQL.Add(string.Format(sbSql_v.ToString()));
                }
                if (MessageBox.Show(string.Format("数据已经就绪,确定要进度完成?"), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    if (LstSQL.Count > 0)
                    {
                        DbHelperSQL.ExecuteSqlTran(LstSQL);
                        MessageBox.Show("上传完毕，请核实!");
                        btnChange_Click(sender, e);
                        btnCopy_Click(sender, e);
                        this.GetDataFromSystem(SAP_MM_P.ALL);
                        this.xtraTabControl1.SelectedTabPageIndex = 0;
                    }
                    else
                    {
                        MessageBox.Show("没有数据要进行登记");
                    }
                }
            }
        }


        private void Upload_F30(object sender, EventArgs e)
        {
            List<PriceMappingList> L = this.gridView_Price.DataSource as List<PriceMappingList>;

            if (MessageBox.Show("确定中文描述上传吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {

                List<string> LstSQL = new List<string>();

                foreach (PriceMappingList itemcode in L)
                {
                    string sbSql_v = string.Format(" exec sp_Upload_SAP_StatusOfProgress @MaterialNumber='{0}',@UploadType='{1}',@CreateUser='{2}',@Values='{3}' ", itemcode.Material.ToUpper().Trim(), "UPLOAD_MAT_F30", txtUserName.Text.Trim(), itemcode.F_F30);
                    LstSQL.Add(string.Format(sbSql_v.ToString()));
                }
                if (MessageBox.Show(string.Format("数据已经就绪,确定要进度完成?"), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    if (LstSQL.Count > 0)
                    {
                        DbHelperSQL.ExecuteSqlTran(LstSQL);
                        MessageBox.Show("上传完毕，请核实!");
                        btnChange_Click(sender, e);
                        btnCopy_Click(sender, e);
                        this.GetDataFromSystem(SAP_MM_P.ALL);
                        this.xtraTabControl1.SelectedTabPageIndex = 0;
                    }
                    else
                    {
                        MessageBox.Show("没有数据要进行登记");
                    }
                }
            }
        }


        private void btn_ProdOrderStatus_Clsd_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("JOB_CLSD", "确定工单Closed吗?");
        }

        private void btn_ProdOrderStatus_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("JOB_OPEN", "确定工单Open吗?");
        }

        private void btn_PCNNOUpload_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("PCN"))) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                DOUploadMaterial_GC_PCN_NO();
            }
        }

        private void bandedGridView3_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.bandedGridView3);
        }

        private void btn_SPY_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("SP_Y", "确定特殊监控吗?");
        }

        private void btn_SPN_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("SP_N", "确定解锁监控吗?");
        }

        private void btn_Var1_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("VAR1", "设置变量【Var1】?");
        }

        private void btn_Var2_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("VAR2", "设置变量【Var2】?");
        }

        private void txt_BIReportName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmPVSelect newform = new frmPVSelect();
            newform.TFormName = "BI Report List";
            newform.TstrTable = "SAP_BIReportName"; // "cv_YearMonth"; 
            newform.TSelFields = "BICode,代码;BIName,报表名称;RecordQty,记录数;Owner,归属人";
            newform.TOrderBY = " Order  by BIName";
            newform.TSpecialWhere = " and FunctionName='MasterData'"; // " And Year*100+Month>=2014*100+11 ";
            newform.Width = 550;
            newform.Height = 700;

            newform.ShowDialog();

            if (newform.TDataRow != null)
            {

                txt_BIReportName.Text = newform.TDataRow["BICode"].ToString();

            }
        }

        private void txt_BIReportName_DoubleClick(object sender, EventArgs e)
        {
            txt_BIReportName.Text = "";
        }

        private void btn_TableToList_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            if ((this.gdc_MpsMain.DataSource as System.Data.DataTable) != null)
            {

                foreach (DataRow dr in (this.gdc_MpsMain.DataSource as System.Data.DataTable).Rows)
                {
                    sb.AppendFormat("{0}{1}", dr["Material_Number"].ToString(), System.Environment.NewLine);
                }
                rch_MaterialList.Text = "";
                rch_MaterialList.AppendText(sb.ToString());
            }
        }

        private void 导出到ExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ExportToExcel(this.gdv_MonitorList, txt_BIReportName.Text);
        }


        private void ExportToExcel(DevExpress.XtraGrid.Views.Grid.GridView gdv, string strFileName)
        {
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "xlsx|xlsx";
            sv.FileName = strFileName + ".xlsx";
            if (sv.ShowDialog() == DialogResult.OK)
            {

                string fileName = sv.FileName;
                if (!fileName.EndsWith(".xls") && !fileName.EndsWith(".xlsx"))
                {
                    fileName = fileName + ".xlsx";
                }
                DevExpress.XtraGrid.Views.Grid.GridView gv = new DevExpress.XtraGrid.Views.Grid.GridView();
                gv = gdv;
                gv.OptionsPrint.AutoWidth = false;
                gv.ExportToXlsx(fileName, new DevExpress.XtraPrinting.XlsxExportOptions() { SheetName = "Sheet1" });
                MessageBox.Show("导出完毕", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void simpleButton3_Click_1(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if ((this.gdc_MasterDataMonitor.DataSource as System.Data.DataTable) != null)
            {
                foreach (DataRow dr in (this.gdc_MasterDataMonitor.DataSource as System.Data.DataTable).Rows)
                {
                    sb.AppendFormat("{0}{1}", dr["Material"].ToString(), System.Environment.NewLine);
                }
                rch_MaterialList.Text = "";
                rch_MaterialList.AppendText(sb.ToString());
            }
        }

        private void gdv_MonitorList_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MonitorList);
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("DELETE_MARC", "确定删除MARC吗?");
        }

        private void rch_MaterialList_DoubleClick(object sender, EventArgs e)
        {
            rch_MaterialList.SelectAll();
        }

        private void btnAdminDeleteSAPList_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(string.Format("确定要处理内部数据【{0}】?", txt_var.Text), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                if (DbHelperSQL.ExecuteSql(string.Format("exec sp_SAP_RemoveData '{0}','{1}'", "Y", txt_var.Text)) > 0)
                {
                    MessageBox.Show("执行完毕可以重新上传数据");
                }
            }
        }

        private void btnCheckPrice_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rch_PriceList.Text);

            sb.Replace("\t\n", "|");
            sb.Replace("\t", "$");
            sb.Replace(" ", "");
            rch_MaterialList.Text = "";
            decimal k = 0;
            List<PriceMappingList> LstPrice = new List<PriceMappingList>();

            foreach (string item in sb.ToString().Split('|'))
            {

                string m = item.Split('$')[0];

                if (item.Split('$').Length <= 1)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(m))
                {
                    continue;
                }
                rch_MaterialList.AppendText(m.Trim());
                rch_MaterialList.AppendText(Environment.NewLine);
                if (decimal.TryParse(item.Split('$')[1], out  k) == false)
                {
                    MessageBox.Show(string.Format("物料{0}，存在价格不正常，请修复", m), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                LstPrice.Add(new PriceMappingList() { Material = m, Price = decimal.Parse(item.Split('$')[1]) });
            }
            this.gridControl_Price.DataSource = LstPrice;
            this.gridView_Price.BestFitColumns();

        }

        public class PriceMappingList
        {

            public string Material { get; set; }

            public decimal Price { get; set; }

            public string CN_Description { get; set; }

            public string F_F30 { get; set; }
        }

        private void gridView_Price_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gridView_Price);
        }

        private void btnPriceUploadForMissingPrice_Click(object sender, EventArgs e)
        {
            List<PriceMappingList> L = this.gridView_Price.DataSource as List<PriceMappingList>;

            if (MessageBox.Show("确定价格上传吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {

                List<string> LstSQL = new List<string>();

                foreach (PriceMappingList itemcode in L)
                {
                    string sbSql_v = string.Format(" exec sp_Upload_SAP_StatusOfProgress @MaterialNumber='{0}',@UploadType='{1}',@CreateUser='{2}',@Values='{3}' ", itemcode.Material.ToUpper().Trim(), "UPLOAD_PRICE", txtUserName.Text.Trim(), itemcode.Price);
                    LstSQL.Add(string.Format(sbSql_v.ToString()));
                }
                if (MessageBox.Show(string.Format("数据已经就绪,确定要进度完成?"), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    if (LstSQL.Count > 0)
                    {
                        DbHelperSQL.ExecuteSqlTran(LstSQL);
                        MessageBox.Show("上传完毕，请核实!");
                        btnChange_Click(sender, e);
                        btnCopy_Click(sender, e);
                        this.GetDataFromSystem(SAP_MM_P.ALL);
                        this.xtraTabControl1.SelectedTabPageIndex = 0;
                    }
                    else
                    {
                        MessageBox.Show("没有数据要进行登记");
                    }
                }
            }


        }

        private void btnClearPrice_Click(object sender, EventArgs e)
        {
            rch_PriceList.Text = "";
            LstSAPUploadList_RCH.Clear();
            this.gdv_price_mass.RefreshData();
            this.gridView_Price.RefreshData();
        }

        private void rch_PriceList_DoubleClick(object sender, EventArgs e)
        {
            rch_PriceList.SelectAll();
        }

        private void btn_DataRegist_Click(object sender, EventArgs e)
        {
            string KeyCode = txt_BIReportName.Text.Split('-')[0].ToUpper().Trim();

            UploadProgress("REGMST", KeyCode, string.Format("登记本次{0}报表操作", KeyCode));
        }

        private void UploadProgress(string uploadType, string KeyCode, string Msg)
        {
            List<string> LstSQL = new List<string>();

            foreach (string itemcode in txt_MaterialNumber.Text.Split(','))
            {
                string sbSql_v = string.Format(" exec sp_Upload_SAP_StatusOfProgress @MaterialNumber='{0}',@UploadType='{1}',@CreateUser='{2}',@Values='{3}' ", itemcode.ToUpper().Trim(), uploadType, txtUserName.Text.Trim(), KeyCode);
                LstSQL.Add(string.Format(sbSql_v.ToString()));
            }
            if (MessageBox.Show(string.Format("确定要进度完成【{0}】?", Msg), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                if (LstSQL.Count > 0)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                    this.GetDataFromSystem(SAP_MM_P.ALL);
                    this.xtraTabControl1.SelectedTabPageIndex = 0;
                }
                else
                {
                    MessageBox.Show("没有数据要进行登记");
                }
            }
        }

        private void btn_CheckAll_Click(object sender, EventArgs e)
        {
         
            DOUploadMaterial_PO_FullVersion_Rch("PO");

        }

        List<SAPItemQueryInfo_RCH> LstSAPUploadList_RCH = new List<SAPItemQueryInfo_RCH>();

        private void DOUploadMaterial_PO_FullVersion_Rch(string UploadType)
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList_RCH.Clear();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (true)
                {
                    this.gridView_Price.Columns.Clear(); 
                   
                    sb.Append(rch_PriceList.Text);

                    sb.Replace("\t\n", "|");
                    sb.Replace("\t", "$");
                    sb.Replace(" ", "");
                    rch_MaterialList.Text = "";
                    decimal k = 0;
                  
                    List<string> LstSQL = new List<string>();
                    foreach (string item in sb.ToString().Split('|'))
                    {
                        string[] dt_excel = item.Split('$');
                        if(dt_excel.Length<=1){break;}
                        string _Material_Number = dt_excel[0].ToString().Trim();
                        string _Material_Description = "";
                        string _Currency = dt_excel[10].ToString();
                        string _MaterialGroup = "";
                        string _PurchasingGroup = dt_excel[8].ToString();
                        string _MRP_Type = dt_excel[12].ToString();
                        string _Procurement_Type = "";
                        string _Special_Procurement_Type = "";
                        string _MRP_Controller = dt_excel[13].ToString();
                        string _Planned_Delivery_Days = dt_excel[11].ToString().ToLower().Replace("days", "").Trim();
                        string _Monetary_Unit = "";
                        string _Purchasing_Cost = dt_excel[9].ToString().Trim();
                        string _Reorder_Point = dt_excel[20].ToString();
                        string _Lot_Size = dt_excel[16].ToString();
                        string _Maximum_Stock_Level = dt_excel[17].ToString();
                        string _Safety_Stock = dt_excel[19].ToString();
                        string _Minimum_Lot_Size = dt_excel[18].ToString();
                        string _Strategy_Group = dt_excel[14].ToString();
                        string _Individual_Collective_Requ = dt_excel[15].ToString();

                        string _Special_Procgeurement_Type_PO = dt_excel[7].ToString();
                        if (_Purchasing_Cost == "") { _Purchasing_Cost = "-1"; }

                        if (decimal.TryParse(_Purchasing_Cost, out  k) == false)
                        {
                            MessageBox.Show(string.Format("物料{0}，存在价格不正常，请修复", _Material_Number), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

 
                        string _Serial_Number = "";
                        string _ProcumentOwner = "";
                        if (!string.IsNullOrEmpty(_Material_Number))
                        {
                            LstSAPUploadList_RCH.Add(new SAPItemQueryInfo_RCH
                            {
                                Material_Number = _Material_Number,
                                Material_Description = _Material_Description,
                                CreatedBy = Commoner.UseName.Trim(),
                                Purchasing_Cost = _Purchasing_Cost.Trim(),
                                PurchasingGroup = _PurchasingGroup.Trim(),
                                MRP_Type = _MRP_Type.Trim(),
                                MRP_Controller = _MRP_Controller.Trim(),
                                Procurement_Type = _Procurement_Type,
                                Special_Procurement_Type = _Special_Procurement_Type.Trim(),
                                Serial_Number = _Serial_Number.Trim(),
                                Upload_Type = UploadType.Trim(),
                                Currency = _Currency.Trim(),
                                Individual_Collective_Requ = _Individual_Collective_Requ.Trim(),
                                MaterialGroup = _MaterialGroup.Trim(),
                                Monetary_Unit = _Monetary_Unit.Trim(),
                                Planned_Delivery_Days = _Planned_Delivery_Days.Trim(),
                                Strategy_Group = _Strategy_Group.Trim(),
                                Lot_Size = _Lot_Size.Trim(),
                                Maximum_Stock_Level = _Maximum_Stock_Level.Trim(),
                                Minimum_Lot_Size = _Minimum_Lot_Size.Trim(),
                                Safety_Stock = _Safety_Stock.Trim(),
                                Reorder_Point = _Reorder_Point.Trim(),
                                ProcurementOwner = _ProcumentOwner.Trim(),
                                Special_Procgeurement_Type_PO = _Special_Procgeurement_Type_PO.Trim(),

                            });
                        }
                    }
                }

                if (chk_KPI.Checked)
                {
                    rch_MaterialList.Text = sb.ToString();
                }

                this.gridControl_price_mass.DataSource = LstSAPUploadList_RCH;
                this.gdv_price_mass.BestFitColumns();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                this.gridControl_price_mass.DataSource = LstSAPUploadList_RCH;
                if (chk_KPI.Checked)
                {
                    rch_MaterialList.Text = sb.ToString();
                }
            }
            finally
            {
                
            }
        }

        private void sb_uploadMRP_Click(object sender, EventArgs e)
        {
            List<string> LstSQL = new List<string>();

            if (LstSAPUploadList_RCH.Count > 0)
            {
                StringBuilder sbm = new StringBuilder();

                foreach (SAPItemQueryInfo_RCH item in LstSAPUploadList_RCH)
                {
                    StringBuilder sbSql_ex = new StringBuilder();
                    sbSql_ex.Append("	EXEC  SP_Upload_SAPMaterialToMonitor_PR  ");
                    sbSql_ex.AppendFormat("	@MaterialNumber='{0}',  ", item.Material_Number);
                    sbSql_ex.AppendFormat("	@PurchasingGroup='{0}', ", item.PurchasingGroup);
                    sbSql_ex.AppendFormat("	@Purchasing_Cost='{0}',  ", item.Purchasing_Cost);
                    sbSql_ex.AppendFormat("	@Currency='{0}',  ", item.Currency);
                    sbSql_ex.AppendFormat("	@Planned_Delivery_Days='{0}',  ", item.Planned_Delivery_Days);
                    sbSql_ex.AppendFormat("	@MRP_Type='{0}', ", item.MRP_Type);
                    sbSql_ex.AppendFormat("	@MRP_Controller='{0}',  ", item.MRP_Controller);
                    sbSql_ex.AppendFormat("	@Strategy_Group='{0}',  ", item.Strategy_Group);
                    sbSql_ex.AppendFormat("	@Individual_Collective_Requ='{0}',  ", item.Individual_Collective_Requ);
                    sbSql_ex.AppendFormat("  @Lot_Size ='{0}', ", item.Lot_Size);
                    sbSql_ex.AppendFormat("  @Maximum_Stock_Level ='{0}', ", item.Maximum_Stock_Level);
                    sbSql_ex.AppendFormat("  @Minimum_Lot_Size ='{0}', ", item.Minimum_Lot_Size);
                    sbSql_ex.AppendFormat("  @Safety_Stock  = '{0}' , ", item.Safety_Stock);
                    sbSql_ex.AppendFormat("  @Reorder_Point  ='{0}', ", item.Reorder_Point);
                    sbSql_ex.AppendFormat("	@UploadType='{0}', ", "PO");
                    sbSql_ex.AppendFormat("	@Special_Procurement_Type_PO='{0}', ", item.Special_Procgeurement_Type_PO.Trim());
                    sbSql_ex.AppendFormat("	@CreateUser='{0}' ", txtUserName.Text);
                    LstSQL.Add(sbSql_ex.ToString());
                    sbm.AppendFormat("{0},", item.Material_Number);
                }

                if (sbm.Length > 0)
                {
                    sbm.Remove(sbm.Length - 1, 1);
                    txt_MaterialNumber.Text = sbm.ToString();
                }
            }
            else
            {
                MessageBox.Show("没有数据要进行登记");
                return;

            }
            if (MessageBox.Show("确定要【采购】进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                DbHelperSQL.ExecuteSqlTran(LstSQL);
                MessageBox.Show("上传完毕，请核实!");
            }
            this.GetDataFromSystem(SAP_MM_P.ALL);

        }

        private void btn_FINRegist_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfProgress("FIN_REG", "确定财务释放吗?");
        }

        private void simpleButton4_Click_1(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rch_MaterialList.Text);
            sb.Replace(".", ".\r\n");
            rch_MaterialList.Text = sb.ToString();
            rch_MaterialList.Text = rch_MaterialList.Text.Substring(0, sb.Length - 1);

        }

        private void btn_Upload_F30_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rch_MaterialList.Text);

            sb.Replace("\t\n", "|");
            sb.Replace("\t", "$");
            sb.Replace(" ", "");
            rch_PriceList.Text = "";
            decimal k = 0;
            List<PriceMappingList> LstPrice = new List<PriceMappingList>();

            foreach (string item in sb.ToString().Split('|'))
            {
                string m = item.Split('$')[0];

                if (item.Split('$').Length <= 1)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(m))
                {
                    continue;
                }
                rch_MaterialList.AppendText(m.Trim());
                rch_MaterialList.AppendText(Environment.NewLine);
                if (String.IsNullOrEmpty(item.Split('$')[1]))
                {
                    MessageBox.Show(string.Format("物料{0}，无F30/F定义，请修复", m), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                LstPrice.Add(new PriceMappingList() { Material = m,  F_F30 = (item.Split('$')[1]), Price = -9999 , CN_Description=""});
            }

            this.gridControl_Price.DataSource = LstPrice;
            this.xtraTabControl1.SelectedTabPage = this.xtraTabPage7;
            this.gridView_Price.BestFitColumns();

            Upload_F30(sender, e);


        }

        private void chk_FIN_CheckedChanged(object sender, EventArgs e)
        {
            InitGrand();
        }

        private void repositoryItemButtonEdit_Log_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow dr = this.gdv_MpsMain.GetFocusedDataRow();
            string material = dr["Material_Number"].ToString();
            frmPVSelect newform = new frmPVSelect();
            newform.TFormName = "日志查询";
            newform.TstrTable = "cv_SAP_ItemMaterilLog"; // "cv_YearMonth"; 
            newform.TSelFields = "Material, 物料代码;Price, 价格记录;CreateDate, 上传日期;Creator, 操作人;Remarks,备注;Procurement_Type,采购类型;MRP_Controller, 控制者;PurchasingCategory,采购归属;Special_Procurement_Type,特殊类型";
            newform.TOrderBY = " Order  by CreateDate";
            newform.TSpecialWhere = " And Material='" + material + "'";
            newform.Width = 700;
            newform.Height = 300;

            newform.ShowDialog();

            
        }

    
    }

    public class SAP_ViewStatus
    {

        public string Material { set; get; }
        public string BASIC_VIEW { set; get; }
        public string SALES { set; get; }
        public string PURCHASING { set; get; }
        public string WORK_SCHEDULING { set; get; }
        public string QUALITY_MANAGEMENT { set; get; }
        public string ACCOUNTING { set; get; }
        public string COSTING { set; get; }
        public string MRP { set; get; }
        public string PLANT_STORAGE_LOC { set; get; }
        public string PROCUREMENT_TYPE { set; get; }
        public string MATERIAL_PLANT_STATUS { set; get; }
        public string COST_PRICE { set; get; }
        public string Crcy { set; get; }
        public string PRODUCT_HIERARCHY { set; get; }
        public string IN_HOUSE_TIME { set; get; }
        public string PLAN_DEL_TIME { set; get; }
        public string MRP_TYPE { set; get; }
        public string STRATEGY_GROUP { set; get; }
        public string BOM_EXIT { set; get; }
        public string ROUTING_EXIT { set; get; }
        public string PRODUCT_HIERARCHY_S { get; set; }
        public string _ENName { get; set; }
        public string _CNName { get; set; }

    }
    public class SAPItemQueryInfo_RCH
    {
       
        public string Material_Number { set; get; }
        public string Material_Description { set; get; }
        public string PriceUnit { set; get; }
        public string Currency { set; get; }
        public string Price { set; get; }
        public string MaterialType { set; get; }
        public string PurchasingGroup { set; get; }
        public string CreatedBy { get; set; }
        public string MRP_Type { set; get; }
        public string PriceControl { set; get; }
        public string Special_Procgeurement_Type { set; get; }
        public string Special_Procgeurement_Type_PO { set; get; }
        public string MRP_Controller { set; get; }
        public string Planned_Delivery_Days { set; get; }
        public string Monetary_Unit { set; get; }
        public string Purchasing_Cost { set; get; }
        public string Backflush { set; get; }
        public string Procurement_Type { get; set; }
        public string MaterialGroup { get; set; }
        public string Reorder_Point { set; get; }
        public string Lot_Size { set; get; }
        public string Maximum_Stock_Level { set; get; }
        public string Safety_Stock { set; get; }
        public string Minimum_Lot_Size { set; get; }
        public string Strategy_Group { set; get; }
        public string Individual_Collective_Requ { set; get; }
        public string Scheduling_Margin { set; get; }
        public string Indicator_Backflush { set; get; }
        public string In_House_Production_Time { set; get; }
        public string Profit_Center { set; get; }
        public string InspectionFlag { set; get; }
        public string Serial_Number { set; get; }
        public string Upload_Type { get; set; }
        public string UpLoad_SQL { get; set; }
        public string MRP_Controller_PL { get; set; }
        public string ProductHierarchy { get; set; }
        public string ProductHierarchyName { get; set; }
        public string Owner { get; set; }
        public string CN_Description { get; set; }
        public string PurchasingCategory { get; set; }
        public string ProcurementOwner { get; set; }
    
  
    
        public string TargetDate { get; set; }
        public string NetPrice { get; set; }
 
        public string Special_Procurement_Type { get; set; }
 

    }
    public class SAPItemQueryInfo
    {
        public string Oid { set; get; }
        public string Plant { set; get; }
        public string Material_Number { set; get; }
        public string Material_Description { set; get; }
        public string PriceUnit { set; get; }
        public string Unit_Issue { set; get; }
        public string Currency { set; get; }
        public string Price { set; get; }
        public string MaterialType { set; get; }
        public string MaterialGroup { set; get; }
        public string LastChange { set; get; }
        public string PurchasingGroup { set; get; }
        public string ABC { set; get; }
        public string MRP_Type { set; get; }
        public string Procurement_Type { set; get; }
        public string ValCl { set; get; }
        public string PriceControl { set; get; }
        public string CreatedBy { set; get; }
        public string ValuationType { set; get; }
        public string CreateDate { set; get; }
        public string Special_Procgeurement_Type { set; get; }
        public string MRP_Controller { set; get; }
        public string Planned_Delivery_Days { set; get; }
        public string Monetary_Unit { set; get; }
        public string Purchasing_Cost { set; get; }
        public string Backflush { set; get; }
        public string GR_Processing_Time { set; get; }
        public string Reorder_Point { set; get; }
        public string Lot_Size { set; get; }
        public string Maximum_Stock_Level { set; get; }
        public string Safety_Stock { set; get; }
        public string Minimum_Lot_Size { set; get; }
        public string Strategy_Group { set; get; }
        public string Individual_Collective_Requ { set; get; }
        public string Scheduling_Margin { set; get; }
        public string Indicator_Backflush { set; get; }
        public string In_House_Production_Time { set; get; }
        public string Profit_Center { set; get; }
        public string InspectionFlag { set; get; }
        public string Serial_Number { set; get; }
        public string Upload_Type { get; set; }
        public string UpLoad_SQL { get; set; }
        public string MRP_Controller_PL { get; set; }
        public string ProductHierarchy { get; set; }
        public string ProductHierarchyName { get; set; }
        public string Owner { get; set; }
        public string CN_Description { get; set; }
        public string PurchasingCategory { get; set; }
        public string ProcurementOwner { get; set; }
        public string Uploaded_By { get; set; }
        public string PCN_NO { get; set; }
        public string _PRODUCT_HIERARCHY_Basic { get; set; }
        public string _ENName { get; set; }
        public string _CNName { get; set; }
        public string DrawingDate  {get;set;}
        public string TargetDate {get;set;}
        public string NetPrice { get; set; }
        public string PIR_User { get; set; }
        public string PIR_Remark { get; set; }
        public string Special_Procurement_Type { get; set; }
        public string PR_Date { get; set; }
        public string Special_Procurement_Type_PO { get; set; }

    }
}